//
//  KSDWebViewController.m
//  KSuodun
//
//  Created by DwZeng on 2022/7/18.
//

#import "KSDWebViewController.h"
#import <WebKit/WebKit.h>

@interface KSDWebViewController ()<WKUIDelegate,WKNavigationDelegate>

/**  webView */
@property(nonatomic , strong) WKWebView * webView;

@property(nonatomic , strong) UIProgressView * progressView;
/**  是否显示进度条(默认显示) */
@property(nonatomic , assign) BOOL hiddenProgress;
/** 打开app的参数 */
@property (strong ,nonatomic) NSDictionary *body;

@end

@implementation KSDWebViewController


- (void)viewDidLoad {
    [super viewDidLoad];

    WKWebViewConfiguration *webConfig = [[WKWebViewConfiguration alloc] init];
    //将所有cookie以document.cookie = 'key=value';形式进行拼接(引号一定要是英文)
    NSString *cookieValue = [self getCookieValue];
    // 加cookie给h5识别，表明在ios端打开该地址
    WKUserContentController* userContentController = WKUserContentController.new;
    WKUserScript * cookieScript = [[WKUserScript alloc]
                                   initWithSource: cookieValue
                                   injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
    webConfig.userContentController = userContentController;
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, navigationHeight, SCREEN_WIDTH, SCREEN_HEIGHT - navigationHeight) configuration:webConfig];
    //    self.webView.allowsBackForwardNavigationGestures = YES;
    
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    
    [self.view addSubview:self.webView];
        
    
    [self loadWithUrl:self.url];

}


-(NSString *)getCookieValue{
    return @"";
}


//加载webView
-(void)loadWithUrl:(NSString *)url{
    NSURL *URL = [NSURL URLWithString:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:URL];
    [self.webView loadRequest:request];
}


///**
// 设置导航栏
// */
//-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
//    decisionHandler(WKNavigationActionPolicyAllow);
//
////    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
////        [self.webView evaluateJavaScript:@"document.title" completionHandler:^(id title, NSError * _Nullable error) {
////            self.navigationTitle = title;
////        }];
//////        if (_webView.webView.canGoBack) {
//////            _closeButton.hidden = NO;
//////        }else{
//////            //            _closeButton.hidden = YES;
//////        }
////    });
//
//    self.url = navigationAction.request.URL.absoluteString;
//
//}

//WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    LOG(@"是否允许这个导航");
    decisionHandler(WKNavigationActionPolicyAllow);
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    //    Decides whether to allow or cancel a navigation after its response is known.
    
    NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;

    NSArray *cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:[response allHeaderFields] forURL:response.URL];
    LOG(@"知道返回内容之后，是否允许加载，允许加载");
    decisionHandler(WKNavigationResponsePolicyAllow);
    NSLog(@"cookies = %@",cookies);

    
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    LOG(@"开始加载");
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
    LOG(@"跳转到其他的服务器");
    
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    LOG(@"网页由于某些原因加载失败");
    
}
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
    LOG(@"网页开始接收网页内容");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    LOG(@"网页导航加载完毕");
    self.navigationTitle = webView.title;
    [webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable ss, NSError * _Nullable error) {
        LOG(@"----document.title:%@---webView title:%@",ss,webView.title);
    }];
//    self.placeholderView.hidden = YES;
    
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    LOG(@"加载失败,失败原因:%@",[error description]);
//    self.placeholderView.hidden = NO;
    
}
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
    LOG(@"网页加载内容进程终止");
//    self.placeholderView.hidden = NO;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
